import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { useState, useEffect } from 'react';
import { Text, StyleSheet } from 'react-native';

const Timer = ({time,setTime,loadSavedGame}) => {

    useEffect(() => {
        if (loadSavedGame) {
            const loadSaveTime = async () => {
                try {
                    const savedTime = await AsyncStorage.getItem('time');
                    if (savedTime) {
                        const time = JSON.parse(savedTime);
                        setTime(time);
                        await AsyncStorage.removeItem('time');
                    }
                } catch (error) {
                    console.error("Error loading time:", error);
                }
            };
            loadSaveTime();
        }
    }, [loadSavedGame]);

    const formatTime = () => {
        const hours = Math.floor(time / 3600);
        const minutes = Math.floor(time / 60);
        const secs = time % 60;
        return `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${secs < 10 ? '0' : ''}${secs}`;
    };

    return (
        <Text style={styles.timer}>{formatTime()}</Text>
    );
};

const styles = StyleSheet.create({
    timer: {
        fontSize: 30,
        fontWeight: 'bold',
        color: "black",
    },
});

export default Timer;